// server/api/user/profile.put.ts
import { defineEventHandler, readBody, getHeader } from 'h3'
import { verifyToken } from '../../utils/auth'

export default defineEventHandler(async (event) => {
  try {
    // Token验证
    const authHeader = getHeader(event, 'authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw createError({
        statusCode: 401,
        statusMessage: '未提供认证令牌'
      })
    }
    
    const token = authHeader.slice(7)
    const decoded = verifyToken(token)
    if (!decoded) {
      throw createError({
        statusCode: 401,
        statusMessage: '令牌无效或已过期'
      })
    }

    const body = await readBody(event)
    const { username, email } = body

    // 获取当前用户ID
    const userId = decoded.userId

    // 验证输入数据
    if (!username && !email) {
      throw createError({
        statusCode: 400,
        statusMessage: '至少需要提供一个更新字段'
      })
    }

    // 检查用户名或邮箱是否已被其他用户使用
    if (username || email) {
      const existingUser = await prisma.user.findFirst({
        where: {
          OR: [
            { username: username || '' },
            { email: email || '' }
          ],
          NOT: { id: userId }
        }
      })
      
      if (existingUser) {
        throw createError({
          statusCode: 409,
          statusMessage: '用户名或邮箱已被其他用户使用'
        })
      }
    }

    // 获取旧用户信息用于记录历史
    const oldUser = await prisma.user.findUnique({
      where: { id: userId }
    })

    if (!oldUser) {
      throw createError({
        statusCode: 404,
        statusMessage: '用户不存在'
      })
    }

    // 准备更新数据
    const updateData: any = {}
    const editHistoryRecords = []

    // 检查并更新用户名
    if (username && username !== oldUser.username) {
      updateData.username = username
      editHistoryRecords.push({
        userId,
        fieldName: 'username',
        oldValue: oldUser.username,
        newValue: username,
        editedBy: userId
      })
    }

    // 检查并更新邮箱
    if (email && email !== oldUser.email) {
      updateData.email = email
      editHistoryRecords.push({
        userId,
        fieldName: 'email',
        oldValue: oldUser.email,
        newValue: email,
        editedBy: userId
      })
    }

    // 如果没有实际更改
    if (Object.keys(updateData).length === 0) {
      return {
        code: 200,
        message: '没有检测到更改',
        data: oldUser
      }
    }

    // 使用事务更新用户信息和记录编辑历史
    const [updatedUser] = await prisma.$transaction([
      // 更新用户信息
      prisma.user.update({
        where: { id: userId },
        data: updateData
      }),
      // 记录编辑历史
      ...editHistoryRecords.map(record => 
        prisma.userEditHistory.create({ data: record })
      )
    ])

    // 移除密码字段
    const { password: _, ...userWithoutPassword } = updatedUser

    return {
      code: 200,
      message: '个人信息更新成功',
      data: userWithoutPassword
    }
    
  } catch (error: any) {
    console.error('更新个人信息错误:', error)
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || '更新失败'
    })
  }
})